import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/servletControll")
public class servletControll extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if(username.isEmpty()) {
            request.setAttribute("error", "你还未输入用户名！");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

        if(password.isEmpty()) {
            request.setAttribute("error", "你还未输入密码！");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

        UserDao userDao = new UserDao();
        User user = userDao.getUserByUsername(username);

        if(user == null || !user.getPassword().equals(password)) {
            request.setAttribute("error", "用户名或密码错误！");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

        request.getSession().setAttribute("user", user);
        response.sendRedirect("success.jsp");
    }

}
